package com.ramblingcoder.bc2.server.tool.update;

import java.io.IOException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.ramblingcoder.bc2.server.tool.update.R;
import com.ramblingcoder.bc2.server.tool.update.commands.SupportingFunctions;
import com.ramblingcoder.bc2.server.tool.update.exceptions.AccessError;
import com.ramblingcoder.bc2.server.tool.update.exceptions.InvalidArguments;
import com.ramblingcoder.bc2.server.tool.update.exceptions.InvalidMapName;
import com.ramblingcoder.bc2.server.tool.update.exceptions.InvalidPlaylist;
import com.ramblingcoder.bc2.server.tool.update.exceptions.LevelNotAvailable;
import com.ramblingcoder.bc2.server.tool.update.exceptions.LogInRequired;
import com.ramblingcoder.bc2.server.tool.update.objects.InfoShare;
import com.ramblingcoder.bc2.server.tool.update.objects.Map;

public class MapView extends Activity implements OnClickListener, OnItemClickListener{
	//Variables-----\
	private Button typeSet, mapAdd, next, restart;
	private EditText rounds;
	private Spinner types, maps;
	private ListView mapList;
	private CheckBox vietnam;
	private Map[] mapSet;
	private Map[] mapOptions;
	//Variables-----/
	
	//Initializer-----\
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
        setContentView(R.layout.mapview);

		types = (Spinner) findViewById(R.id.types);
		maps = (Spinner) findViewById(R.id.maps);

		mapList = (ListView) findViewById(R.id.maplists);
		
		rounds = (EditText) findViewById(R.id.rounds);
		
        typeSet = (Button) findViewById(R.id.set);
        mapAdd = (Button) findViewById(R.id.add);
        next = (Button) findViewById(R.id.next);
        restart = (Button) findViewById(R.id.restart);

        vietnam = (CheckBox) findViewById(R.id.vietnam);
        
        try {
			populate();
		} catch (IOException e) {
			SupportingFunctions.showError(this, e.getMessage(), new Intent(this, BC2ServerChoice.class));
		} catch (LogInRequired e) {
			SupportingFunctions.showError(this, e.getMessage(), new Intent(this, BC2ServerChoice.class));
		} catch (InvalidArguments e) {
			SupportingFunctions.showError(this, e.getMessage(), new Intent(this, BC2ServerChoice.class));
		}
		
		typeSet.setOnClickListener(this);
		mapAdd.setOnClickListener(this);
		next.setOnClickListener(this);
		restart.setOnClickListener(this);
		vietnam.setOnClickListener(this);
	}
	
	public boolean onCreateOptionsMenu(Menu menu) {
	    menu.add(1, 5, 0, "Main Menu");
	    menu.add(1, 0, 0, "Refresh");
	    menu.add(1, 1, 0, "Players View");
	    menu.add(1, 2, 0, "Bans View");
	    menu.add(1, 3, 0, "Settings View");
	    menu.add(1, 4, 0, "Chat View");
	    menu.add(1, 6, 0, "Reserved View");
	    return true;
	}
	
	public boolean onOptionsItemSelected(MenuItem item) {
	    switch (item.getItemId()) {
	    case 5:	
	    	finish();
	    	startActivity(new Intent(this, BC2ServerChoice.class));
	    	break;
	    case 0:
	    	finish();
	    	startActivity(new Intent(this, MapView.class));
	    	break;
	    case 1:	
	    	finish();
	    	startActivity(new Intent(this, PlayerView.class));
	    	break;
	    case 2:	
	    	finish();
	    	startActivity(new Intent(this, BanView.class));
	    	break;
	    case 3:
	    	finish();
	    	startActivity(new Intent(this, SettingsView.class));
	    	break;
	    case 4:
	    	finish();
	    	startActivity(new Intent(this, ChatView.class));
	    	break;
	    case 6:
	    	finish();
	    	startActivity(new Intent(this, ReservedView.class));
	    	break;
	    }
	    return true;
	}

	private void populate() throws IOException, LogInRequired, InvalidArguments {
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		types.setAdapter(adapter);
		
		for (String type : Map.TYPES)
			adapter.add(type);
		
		//-----
		
		int type = Map.getPlaylist(InfoShare.getCommand());
		types.setSelection(type);
		
		//-----
		
		adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
		mapList.setAdapter(adapter);
		
		mapSet = Map.listMaps(InfoShare.getCommand());
		
		for (Map map : mapSet){
			String display = map.getExternalName();
			
			if (map.getRounds() != 0){
				display += " (" + map.getRounds();
				
				if (map.getRounds() == 1)
					display += " Round)";
				else 
					display += " Rounds)";
			}
			
			adapter.add(display);
		}
		
		mapList.setOnItemClickListener(this);
		
		//-----
		
		adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		maps.setAdapter(adapter);
		
		mapOptions = Map.getMaps(type, Map.EXPANSION_ORIGINAL);
		
		for (Map map : mapOptions)
			adapter.add(map.getExternalName());
		
		//-----
		
		Map curr = Map.currentMap(InfoShare.getCommand());
		((TextView) findViewById(R.id.title)).setText("Map : " + curr.getExternalName() + " | Rounds: " + Map.getCurrentRound(InfoShare.getCommand()) + " of " + Map.getMaxRounds(InfoShare.getCommand()));
	}
	//Processes-----/
	
	//Events-----\
	public void onClick(View v) {
		try {
			int expansion = (vietnam.isChecked() ? Map.EXPANSION_VIETNAM : Map.EXPANSION_ORIGINAL);
			
			if (v.getId() == R.id.set){
				if (Map.updateType(InfoShare.getCommand(), types.getSelectedItemPosition(), expansion))
					SupportingFunctions.showMessage(this, "Success.", "Game type successfuly set and default playlist loaded.", new Intent(this, MapView.class));
			} else if (v.getId() == R.id.add){
				Map newMap = mapOptions[maps.getSelectedItemPosition()];
				
				if (rounds.getText().toString().trim().equals(""))
					newMap.setRounds(0);
				else if (Integer.parseInt(rounds.getText().toString()) == 0)
					newMap.setRounds(0);
				else
					newMap.setRounds(Integer.parseInt(rounds.getText().toString()));
				
				if (Map.commitMaps(InfoShare.getCommand(), mapSet, newMap))
					SupportingFunctions.showMessage(this, "Success.", "Map successfuly added.", new Intent(this, MapView.class));
			} else if (v.getId() == R.id.next){
				if (Map.nextMap(InfoShare.getCommand()))
					SupportingFunctions.showMessage(this, "Success.", "Next map started.", new Intent(this, MapView.class));
			} else if (v.getId() == R.id.restart){
				if (Map.restartMap(InfoShare.getCommand()))
					SupportingFunctions.showMessage(this, "Success.", "Current map restarted.", new Intent(this, MapView.class));
			} else if (v.getId() == R.id.vietnam){
				ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item);
				adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item);
				adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				maps.setAdapter(adapter);
				
				mapOptions = Map.getMaps(0, expansion);
				
				for (Map map : mapOptions)
					adapter.add(map.getExternalName());
			}
		} catch (IOException e) {
			SupportingFunctions.showError(this, e.getMessage(), new Intent(this, BC2ServerChoice.class));
		} catch (InvalidArguments e) {
			SupportingFunctions.showError(this, e.getMessage());
		} catch (LogInRequired e) {
			SupportingFunctions.showError(this, e.getMessage(), new Intent(this, BC2ServerChoice.class));
		} catch (LevelNotAvailable e) {
			SupportingFunctions.showError(this, e.getMessage());
		} catch (InvalidMapName e) {
			SupportingFunctions.showError(this, e.getMessage());
		} catch (AccessError e) {
			SupportingFunctions.showError(this, e.getMessage());
		} catch (InvalidPlaylist e) {
			SupportingFunctions.showError(this, e.getMessage());
		}
	}
	
	public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		
		builder.setTitle("Remove Map");
		builder.setMessage("Remove " + mapSet[position].getExternalName()+"?");
		
        builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				try {
					Map temp = mapSet[position];
					mapSet[position] = null;
					
					if (Map.commitMaps(InfoShare.getCommand(), mapSet, null))
						SupportingFunctions.showMessage(MapView.this, "Success", "Map removed successfully.", new Intent(MapView.this, MapView.class));
					else
						mapSet[position] = temp;
				} catch (IOException e) {
					SupportingFunctions.showError(MapView.this, e.getMessage(), new Intent(MapView.this, BC2ServerChoice.class));
				} catch (InvalidArguments e) {
					SupportingFunctions.showError(MapView.this, e.getMessage());
				} catch (LogInRequired e) {
					SupportingFunctions.showError(MapView.this, e.getMessage(), new Intent(MapView.this, BC2ServerChoice.class));
				} catch (InvalidMapName e) {
					SupportingFunctions.showError(MapView.this, e.getMessage());
				} catch (AccessError e) {
					SupportingFunctions.showError(MapView.this, e.getMessage());
				}
			}
		}); 
        
        builder.setNegativeButton("Cancel", null); 
		
        builder.show();
	}
    
    public boolean onKeyDown(int keyCode, KeyEvent event)  {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
        	finish();
        	startActivity(new Intent(this, PlayerView.class));
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }
	//Events-----/
}
